﻿#if UNITY_EDITOR

using UnityEditor;
using UnityEngine;

namespace AI.Graph.Editor {


    public class PortContextEvent : GraphEvent {

        private GenericMenu m_menu;


        public override void OnProcess (Event e) {
            if (m_menu != null) {
                m_menu.ShowAsContext ();
                m_menu = null;
            }


            if (e.IsMouseDown (MouseButton.Right) && e.IsMouseInsideRect (canvas.unscaledRect)) {
                for (int i = 0; i < canvas.nodes.Length; i++) {
                    Node currentNode = canvas.nodes[i];
                    ConnectionPort[] nodePorts = currentNode.ports;

                    for (int j = 0; j < nodePorts.Length; j++) {
                        ConnectionPort currentPort = nodePorts[j];

                        if (!currentNode.isHidden && currentPort.rect.Contains (canvas.mousePosition)) {
                            m_menu = new GenericMenu ();

                            // save values.
                            ConnectionPort portToDisconnect = currentPort;
                            ConnectionPort[] oldConnections = portToDisconnect.connectedPorts;
                            string itemName = currentPort.connectionCount > 1 ? "Remove Connections" : "Remove Connection";
                            string recordTitle = "All Connections of the port: [" + currentPort.name + "] of the node: [" + currentPort.node.name + "] were removed";


                            if (currentPort.hasConnections) {
                                m_menu.AddItem (new GUIContent (itemName), false, () => {
                                    GraphUndo.RecordAndPerform (recordTitle,
                                        () => { Serializer.DisconnectAllPorts (portToDisconnect); },
                                        () => {
                                            for (int p = 0; p < oldConnections.Length; p++) {
                                                Serializer.ConnectPorts (portToDisconnect, oldConnections[p]);
                                            }
                                        });
                                });
                            }
                            else {
                                m_menu.AddDisabledItem (new GUIContent (itemName), false);
                            }

                            e.Use ();
                            return;
                        }
                    }
                }
            }
        }

    }


}
#endif